package com.spider.im.chat;
//13892364593
import com.google.protobuf.ByteString;
import com.spider.im.chat.proto.ChatProto;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;

public class IMClient {
    private final String host;
    private final int port;

    public IMClient(String host, int port) {
        this.host = host;
        this.port = port;
    }

    public void run() throws Exception {

        EventLoopGroup group = new NioEventLoopGroup();

        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) {
                            ChannelPipeline pipeline = ch.pipeline();

                            // Protobuf 编解码器
//                            pipeline.addLast(new ProtobufVarint32FrameDecoder());
//                            pipeline.addLast(new ProtobufDecoder(ChatProto.MessageWrapper.getDefaultInstance()));
//
//                            pipeline.addLast(new ProtobufVarint32LengthFieldPrepender());
//                            pipeline.addLast(new ProtobufEncoder());
                            pipeline.addLast(new HttpServerCodec());
                            pipeline.addLast(new HttpObjectAggregator(65536));
                            pipeline.addLast(new WebSocketServerProtocolHandler("/ws"));
                            // 自定义处理逻辑
                            pipeline.addLast(new IMClientHandler());
                        }
                    });

            Channel channel = bootstrap.connect(host, port).sync().channel();
            // 构造 PrivateChatRequest 消息
            ChatProto.PrivateChatRequest request = ChatProto.PrivateChatRequest.newBuilder()
                    .setSender(1)
                    .setReceiver(2)
                    .build();

            // 封装到 MessageWrapper 中
            ChatProto.MessageWrapper wrapper = ChatProto.MessageWrapper.newBuilder()
                    .setType(ChatProto.MessageType.PRIVATE_CHAT)
                    .setPayload(request.toByteString())
                    .build();

            // 发送消息
//            channel.writeAndFlush(new TextWebSocketFrame("连接请求")).sync();
            // 将 protobuf 消息序列化为 ByteString
            ByteString byteString = wrapper.toByteString();
            // 将 ByteString 转换为 ByteBuf
            ByteBuf bufferResp = channel.alloc().buffer(byteString.size());
            bufferResp.writeBytes(byteString.asReadOnlyByteBuffer());
            // 发送消息
            channel.writeAndFlush(new BinaryWebSocketFrame(bufferResp));
            // 保持连接直到关闭
            channel.closeFuture().sync();

        } finally {
            group.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws Exception {
        new IMClient("localhost", 8090).run();
    }
}
